Cuestionario Ampliado del Censo de Población y Vivienda 2020

El cuestionario ampliado se guarda en un un archivo .RData.

data <- read_sav("~/Personas_Censo 2020.SAV")

save(data, 
      file = paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

load(paste0(here::here(), "/Bases/Censo_Personas_2020.RData"))

mydata <- data %>%
           select(CVE_ENT, ENT, MUN, CVE_MUN, ENT_PAIS_RES_5A, MUN_RES_5A, CVE_MUN_RES15, 
                  ENT_PAIS_NAC, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,  
                  ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, EDAD, SEXO, AFRODES, HLENGUA, QDIALECT_INALI, 
                  PERTE_INDIGENA, ALFABET, CAUSA_MIG, SITUA_CONYUGAL, HIJOS_NAC_VIVOS, 
                  CONACT, OCUPACION_C, SITTRA, VACACIONES, SERVICIO_MEDICO, INCAP_SUELDO, INGTRMEN, 
                  ACTIVIDADES_C, TIE_TRASLADO_TRAB, MED_TRASLADO_TRAB1, MED_TRASLADO_TRAB2, MED_TRASLADO_TRAB3,
                  ASISTEN, NIVACAD, ESCOLARI, ESCOACUM,  NOMCAR_C, TIE_TRASLADO_ESCU, 
                  MED_TRASLADO_ESC1, MED_TRASLADO_ESC2, MED_TRASLADO_ESC3,
                  FACTOR, ESTRATO, UPM) 

Zonas Metropolitanas 2020

Se anexa la base de datos de las Zonas Metropolitanas 2020 a la base orginal

ZM_2020 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2020.xlsx"), 
                      startRow = 7, 
                       skipEmptyRows = TRUE) %>%
            select(CVE_ZM, NOM_ZM, CVE_ENT, NOM_ENT, CVE_MUN, NOM_MUN, MC, CF) %>%
             mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                    CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Se asignan las claves de las zonas metropolitanas de acuerdo a las diferentes variables de interes: - Residencia hace 5 años - Laboral - Estudiantil - Nacimiento

mydata <- mydata %>%
          # Zonas Metropolitanas por residenicia
           left_join(., ZM_2020 %>% select(-CVE_ENT), by = c("CVE_MUN")) %>%
           # Zonas Metropolitanas en el lugar de residencia hace 5 años
            left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>% 
                          rename("CVE_ZM_RES15" = "CVE_ZM",
                                 "ZM_RES15" = "NOM_ZM",
                                 "MC_RES15" = "MC",
                                 "CF_RES15" = "CF"), by = c("CVE_MUN_RES15" = "CVE_MUN")) %>%
            # Zonas Metropolitanas en el lugar de trabajo
             left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>%
                           rename("CVE_ZM_ASI" = "CVE_ZM",
                                  "ZM_ASI" = "NOM_ZM",
                                  "MC_TRABAJO" = "MC",
                                  "CF_TRABAJO" = "CF"), by = c("CVE_MUN_ASI" = "CVE_MUN")) %>%
             # Zonas Metropolitanas en el lugar de estudio
              left_join(., ZM_2020 %>% select(-CVE_ENT, -NOM_ENT, -NOM_MUN) %>%
                            rename("CVE_ZM_ASI" = "CVE_ZM",
                                   "ZM_ASI" = "NOM_ZM",
                                   "MC_ASI" = "MC",
                                   "CF_ASI" = "CF"), by = c("CVE_MUN_ASI" = "CVE_MUN"))

save(mydata, file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2020.RData"))          

✔️A partir de aquí se pueden correr los códidos 👇. Se carga el archivo Migracion por Zonas Metropolitanas_2020.RData.

load(file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2020.RData"))

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>%
           select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN,ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, 
                  EDAD, CONACT, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1) 

# Se vuelve a cargar la base de datos para fines practicos
ZM_2020 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2020.xlsx"), 
                      startRow = 7, 
                       skipEmptyRows = TRUE) %>%
            mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                   CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Entidades y Municipios

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios, pero es importante hacer notar que tres municipios no entraron el muestreo del Cuestionario Ampliado.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)
nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")
est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2020.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()
#saveRDS(MUN, file = paste0(here::here(), "/Bases/municipios_2020.RDS"))

# Claves de las zonas metropolitanas
zm <- sjlabelled::get_labels(mydata$CVE_ZM)[-2]
nom_zm <- sjlabelled::get_labels(mydata$NOM_ZM)[-2]

Movilidad estudiantil

Movilidad interna

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

table(MC$I_ZM)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_municipal.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 5 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel municipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 274602 37 0 0 1366 122 101 12 0 240 579 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 662 13095 0 0 0 22 272 0 0 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 509 0 13315 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 128 3 0 4370 2 24 319 0 0 3 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7139 36 45 0 29323 121 88 0 0 11 275 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 706 0 24 0 96 11641 510 95 10 0 163 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 559 0 0 32 9 312 15896 8 22 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 74 0 0 0 0 70 38 2489 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 158 27 4 0 0 173 264 0 5605 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 176 0 0 0 0 0 0 0 0 5129 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2162 3 0 0 431 233 196 0 0 5 14930 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 112987 148 0 262 80 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 16 266099 76 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 40 119 24958 1035 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 251 81 1979 459410 1321 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 80 25 78 1909 27084 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28950 0 0 0 0 0 0 0 0 0 0 0 0
003001 8 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 19295 0 43 0 7 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 260 13 0 0 0 0 0 14139 31 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 75849 146 20 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 0 0 0 0 284 92491 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 8 0 4461 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15975 298 36 23 195 18 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 102 79728 0 38 37 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 64557 11 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 343 37 21417 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 366 489 5 0 7948 14 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 263 0 0 0 9290 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 11 0 0 0 2252
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 227 2 0 44 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 
#### Filtro de estados <<<<< filter(value >= 100000000000) %>% 
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios,
#                filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
################################################################################
tabla1 <- migration_flows_metropolitan(tabla = Migrantes, 
                                       filtro_zm = ZM, 
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       Emigrantes = Emigrantes, 
                                       Inmigrantes = Inmigrantes, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#                              }
 #                                          
#})

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio", 
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio", 
                                  Emigrantes = "%Entran por estudio") 

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel municipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (municipal).pdf"

## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.2,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel municipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2020 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (municipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM = ZM, tabla = Migrantes)

Emigrantes <- Emigrantes_function(ZM = ZM, tabla = Migrantes)
    
################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 18000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 6000) %>% 
                      pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = filtro_est, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "Otros estados") %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 
# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (municipal).pdf"

## Gráficos a nivel zona metropolitana (ZMVM)
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.25,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.15, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 3, 
                    clock.wise = TRUE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM = ZM, tabla = Migrantes)

Emigrantes <- Emigrantes_function(ZM = ZM, tabla = Migrantes)  

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 18000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 6000) %>% 
                      pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = filtro_est, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "Otros estados") 

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 


# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()
# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (municipal).pdf"

## Gráficos a nivel zona metropolitana (ZMVM)
chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.25,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = TRUE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15, 
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 20, 
                         group4 = grupo4, 
                         group4.text = "Otro municipios",
                         group4.col = 30)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZMVM a nivel municipal.pdf"

## Etiquetas a nivel zona metropolitana (ZMVM)
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                      group_by(rn) %>% 
                       summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 50), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 50) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.7,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (municipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (municipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (municipal).RData"))
Indicadores de Movilidad estudiantil
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 274 602 3 139 16 133 −12 994 19 272 0.68 3.494 −2.8 −32 266
001002 51 474 48 275 13 095 1 173 493 680 1 666 4.70 1.977 2.7 −986
001003 58 155 55 019 13 315 567 119 448 686 2.00 0.421 1.6 −238
001004 16 997 15 959 4 370 516 209 307 725 6.26 2.537 3.7 −418
001005 129 859 122 544 29 323 7 830 1 915 5 915 9 745 12.41 3.035 9.4 −3 830
001006 47 557 44 893 11 641 1 630 1 084 546 2 714 7.05 4.690 2.4 −2 168
001007 57 269 53 484 15 896 990 2 295 −1 305 3 285 3.58 8.289 −4.7 −4 590
001008 9 552 8 868 2 489 196 118 78 314 4.26 2.562 1.7 −236
001009 22 461 21 182 5 605 644 35 609 679 5.90 0.321 5.6 −70
001010 20 382 18 987 5 129 193 465 −272 658 1.96 4.725 −2.8 −930
001011 61 986 57 999 14 930 3 075 1 061 2 014 4 136 10.25 3.537 6.7 −2 122
002001 440 624 422 238 112 987 638 857 −219 1 495 0.30 0.397 −0.1 −1 714
002002 1 042 395 1 004 592 266 099 596 870 −274 1 466 0.12 0.170 −0.1 −1 740
002003 102 896 98 206 24 958 1 260 2 136 −876 3 396 2.51 4.249 −1.7 −4 272
002004 1 910 568 1 829 472 459 410 4 038 3 468 570 7 506 0.43 0.371 0.1 −6 936
002005 126 264 121 701 27 084 2 092 1 401 691 3 493 3.37 2.260 1.1 −2 802
002006 117 050 109 811 28 950 0 0 0 0 0.00 0.000 0.0 0
003001 72 358 69 371 19 295 75 5 70 80 0.21 0.014 0.2 −10
003002 62 884 59 781 14 139 316 7 309 323 1.03 0.023 1.0 −14
003003 290 063 279 213 75 849 462 495 −33 957 0.32 0.348 0.0 −990
Fuente: Estimaciones del CONAPO.

Movilidad intramunicipal

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intramunicipal.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 5 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel intramunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 002006 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007
001001 274602 0 0 0 1366 0 0 0 0 0 579 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 0 13095 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 13315 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 4370 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7139 0 0 0 29323 0 0 0 0 0 275 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 11641 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 15896 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 2489 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 5605 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 5129 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 2162 0 0 0 431 0 0 0 0 0 14930 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 112987 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 266099 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 24958 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 459410 1321 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1909 27084 0 0 0 0 0 0 0 0 0 0 0 0 0
002006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28950 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19295 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 14139 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 75849 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 92491 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4461 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15975 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79728 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64557 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 21417 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7948 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9290 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2252
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Matrices por zonas metropolitanas

MR <- NULL
for(i in 1:length(zm)){
tabla <- ZM_2020 %>%
          select(CVE_ZM, CVE_MUN) %>%
           filter(CVE_ZM %in% zm[i]) %>%
            pull(CVE_MUN)

MR[[paste0(zm[i])]] <- Migrantes %>%
                        as.data.frame() %>%
                         tibble::rownames_to_column(var = "CVE_MUN") %>%
                          mutate_if(is.numeric, as.numeric) %>%
                           select(CVE_MUN, all_of(tabla)) %>%
                            filter(CVE_MUN %in% tabla)
}

# Se guardan en un objeto de R 
saveRDS(MR, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2020.RDS"))

# Se genera un Excel con todas las matrices por ZM
wb <- createWorkbook()
for(i in 1:length(zm)){
addWorksheet(wb, paste0(zm[i]))
writeData(wb, i, MR[[paste0(zm[i])]] %>% as.data.frame())
saveWorkbook(wb, 
              file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2020.xlsx"), 
               overwrite = TRUE)
}

Matriz de Movilidad estudiantil en la Zona Metropolitana de Cuernavaca, 2015 - 2020

Matriz de Movilidad estudiantil a nivel intramunicipal
Zona Metropolitana de Cuernavaca
CVE_MUN 017007 017008 017009 017011 017018 017020 017028 017029 017034 017035
017007 89612 911 142 1671 1816 170 0 30 0 72
017008 5262 19610 0 2251 986 0 411 79 0 25
017009 1965 12 4315 20 15 7 0 0 0 0
017011 10197 27 0 43035 459 27 16 470 0 0
017018 4542 558 0 241 24522 0 57 0 0 56
017020 2150 50 8 1585 0 8083 0 812 0 0
017028 1641 276 0 79 1535 5 12603 15 0 114
017029 1329 33 0 740 0 159 0 21156 0 0
017034 74 4 0 0 38 0 4 0 1935 4
017035 179 4 0 0 12 0 4 0 0 5416
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 3) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################# Filtro #########################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 

#p <- data.frame(ZM = ZM_CF,
 #               filtro_municipio = filtro_mig)

#write.table(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intramunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
tabla1 <- intramunicipal_flows_metropolitan(filtro_zm = ZM, 
                                            filtro_mig = filtro_mig, 
                                            Emigrantes = Emigrantes,
                                            Inmigrantes = Inmigrantes, 
                                            category_group = estados, 
                                            group = "Otros municipios")

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                                             tabla1[[i]] %>%
#                                              as.data.frame() %>%
#                                               adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#})

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (Intramunicipal).pdf"

## Gráficos a nivel intramunicipal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel intramunicipal.pdf"

file = "/Graficos/prueba.pdf"
labels_chord_diagram(file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2020 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (Intramunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>% 
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 13000) %>% 
               pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = NULL, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "ZMVM") %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%                        
            column_to_rownames(., var = "rn")   
# Paleta de colores
groupColors <- paste0(colorRampPalette(paleta)(length(unique(c(colnames(tabla1), rownames(tabla1))))), "7F")

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (Intramunicipal).pdf"

## Gráficos a nivel zona metropolitana (ZMVM)
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.25,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.1, 0.5),
                    adj.ylim = 0.2,
                    gap.degree = 3, 
                    clock.wise = TRUE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes) 

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 13000) %>% 
               pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = NULL, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "ZMVM") 
tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (Intramunicipal).pdf"

chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.25,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = TRUE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15,
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 30)

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZMVM a nivel intramunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)  

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 50), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 50) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.7,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (Intramunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intramunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intramunicipal).RData"))
Indicadores de Movilidad estudiantil
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 274 602 1 945 9 301 −7 356 11 246 0.42 2.0 −1.6 −18 602
001002 51 474 48 275 13 095 0 0 0 0 0.00 0.0 0.0 0
001003 58 155 55 019 13 315 0 0 0 0 0.00 0.0 0.0 0
001004 16 997 15 959 4 370 0 0 0 0 0.00 0.0 0.0 0
001005 129 859 122 544 29 323 7 414 1 797 5 617 9 211 11.75 2.8 8.9 −3 594
001006 47 557 44 893 11 641 0 0 0 0 0.00 0.0 0.0 0
001007 57 269 53 484 15 896 0 0 0 0 0.00 0.0 0.0 0
001008 9 552 8 868 2 489 0 0 0 0 0.00 0.0 0.0 0
001009 22 461 21 182 5 605 0 0 0 0 0.00 0.0 0.0 0
001010 20 382 18 987 5 129 0 0 0 0 0.00 0.0 0.0 0
001011 61 986 57 999 14 930 2 593 854 1 739 3 447 8.64 2.8 5.8 −1 708
002001 440 624 422 238 112 987 0 0 0 0 0.00 0.0 0.0 0
002002 1 042 395 1 004 592 266 099 0 0 0 0 0.00 0.0 0.0 0
002003 102 896 98 206 24 958 0 0 0 0 0.00 0.0 0.0 0
002004 1 910 568 1 829 472 459 410 1 321 1 909 −588 3 230 0.14 0.2 −0.1 −3 818
002005 126 264 121 701 27 084 1 909 1 321 588 3 230 3.08 2.1 0.9 −2 642
002006 117 050 109 811 28 950 0 0 0 0 0.00 0.0 0.0 0
003001 72 358 69 371 19 295 0 0 0 0 0.00 0.0 0.0 0
003002 62 884 59 781 14 139 0 0 0 0 0.00 0.0 0.0 0
003003 290 063 279 213 75 849 0 0 0 0 0.00 0.0 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermunicipal

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intermunicipal.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 3 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel intermunicipal
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 0 37 0 0 0 122 101 12 0 240 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 662 0 0 0 0 22 272 0 0 67 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 509 0 0 0 0 0 0 0 0 21 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 128 3 0 0 2 24 319 0 0 3 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 36 45 0 0 121 88 0 0 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 706 0 24 0 96 0 510 95 10 0 163 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 559 0 0 32 9 312 0 8 22 0 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 74 0 0 0 0 70 38 0 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 158 27 4 0 0 173 264 0 0 3 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 176 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 3 0 0 0 233 196 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 0 148 0 262 80 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 16 0 76 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 40 119 0 1035 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 251 81 1979 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 80 25 78 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 8 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 43 0 7 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 260 13 0 0 0 0 0 31 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 40 0 0 0 0 0 0 0 146 20 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 0 0 0 284 0 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 8 0 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 298 36 23 195 18 0 45
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 102 0 0 38 37 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 0 11 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 343 37 0 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 366 489 5 0 0 14 0 26
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 263 0 0 0 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 11 0 0 0 0 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 37 227 2 0 44 0 0 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 162 45 27 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0) %>%
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios,
#                filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
tabla1 <- migration_flows_metropolitan(tabla = Migrantes, 
                                       filtro_zm = ZM, 
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       Emigrantes = Emigrantes, 
                                       Inmigrantes = Inmigrantes, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group = "Otros estados")

################################################################################
## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/100) %>%
#                                                    pull(Total)
#                              }
#                                           })


## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 0.
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (Intermunicipal).pdf"

## Gráficos a nivel intermunicipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2020 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)
             

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2020 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      mutate(rn = case_when(.$rn %in% ZM ~ .$rn,
                                                            .$rn %nin% ZM ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))])),
                                             cn = case_when(.$cn %in% ZM ~ .$cn,
                                                            .$cn %nin% ZM ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]))) %>%
                                       filter(value > 0) 
  }
) 
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                geom_stratum(aes(fill = cn), 
                              color = "white", 
                               alpha = 0.65,  
                                lwd = 0.001, 
                                 width = 1/5,
                                  reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (Intermunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 500) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = filtro_est, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "Otros estados") %>%
            dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%                        
            column_to_rownames(., var = "rn")    
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (Intermunicipal).pdf"

## Gráficos a nivel estatal 
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.25,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.1, 0.5),
                    adj.ylim = 0.2,
                    gap.degree = 3, 
                    clock.wise = FALSE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames


## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 500) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = filtro_est, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "Otros estados") 

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (Intermunicipal).pdf"

chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.25,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = FALSE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15, 
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 20, 
                         group4 = grupo4, 
                         group4.text = "Otro municipios",
                         group4.col = 30)

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZMVM a nivel intermunicipal.pdf"

labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2020 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes  <- Migrantes %>%
                 as.data.frame() %>%
                  tibble::rownames_to_column(var = "rn") %>% 
                   melt(., id.vars = "rn", variable.name = "cn") %>%
                    mutate_if(is.factor, as.character) %>%
                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                      filter(value > 0) %>%
                      group_by(rn) %>% 
                       summarise(Inmigrantes = sum(value, na.rm = TRUE)) 

Emigrantes <- Migrantes %>%
               as.data.frame() %>%
                tibble::rownames_to_column(var = "rn") %>% 
                 melt(., id.vars = "rn", variable.name = "cn") %>%
                  mutate_if(is.factor, as.character) %>%
                   mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                    filter(value > 0) %>%
                     group_by(cn) %>% 
                      summarise(Emigrantes = sum(value, na.rm = TRUE))     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(rn %in% ZM) %>%
               filter(value > 30000) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)
#########################################################################################

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ .$rn,
                                     .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                       
                      cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ .$cn,
                                     .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                filter(value > 0) 


p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (Intermunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2020.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar v
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intermunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intermunicipal).RData"))
Indicadores de Movilidad estudiantil
Zonas Metropolitanas
Clave del municipio Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 945 506 901 262 0 1 194 6 832 −5 638 8 026 0.26 1.480 −1.2 −13 664
001002 51 474 48 275 0 1 173 493 680 1 666 4.70 1.977 2.7 −986
001003 58 155 55 019 0 567 119 448 686 2.00 0.421 1.6 −238
001004 16 997 15 959 0 516 209 307 725 6.26 2.537 3.7 −418
001005 129 859 122 544 0 416 118 298 534 0.66 0.187 0.5 −236
001006 47 557 44 893 0 1 630 1 084 546 2 714 7.05 4.690 2.4 −2 168
001007 57 269 53 484 0 990 2 295 −1 305 3 285 3.58 8.289 −4.7 −4 590
001008 9 552 8 868 0 196 118 78 314 4.26 2.562 1.7 −236
001009 22 461 21 182 0 644 35 609 679 5.90 0.321 5.6 −70
001010 20 382 18 987 0 193 465 −272 658 1.96 4.725 −2.8 −930
001011 61 986 57 999 0 482 207 275 689 1.61 0.690 0.9 −414
002001 440 624 422 238 0 638 857 −219 1 495 0.30 0.397 −0.1 −1 714
002002 1 042 395 1 004 592 0 596 870 −274 1 466 0.12 0.170 −0.1 −1 740
002003 102 896 98 206 0 1 260 2 136 −876 3 396 2.51 4.249 −1.7 −4 272
002004 1 910 568 1 829 472 0 2 717 1 559 1 158 4 276 0.29 0.167 0.1 −3 118
002005 126 264 121 701 0 183 80 103 263 0.30 0.129 0.2 −160
002006 117 050 109 811 0 0 0 0 0 0 0 0 0
003001 72 358 69 371 0 75 5 70 80 0.21 0.014 0.2 −10
003002 62 884 59 781 0 316 7 309 323 1.03 0.023 1.0 −14
003003 290 063 279 213 0 462 495 −33 957 0.32 0.348 0.0 −990
Fuente: Estimaciones del CONAPO.

Movilidad metropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_metropolitana.RDS"))

Matrices

Se genera una matriz cruzada del lugar de residencia hace 5 años a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_metropolitana.RDS"))

Migrantes <- svytable(~CVE_ZM_ASI + CVE_ZM, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ZM, CVE_ZM_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_ZM" = "row_labels") %>% 
                  arrange(CVE_ZM) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_ZM = substr(.$CVE_ZM, 8, 12)) %>% 
              pull(CVE_ZM)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_ZM" = ".") %>%
                mutate(`CVE_ZM` = substr(.$CVE_ZM, 12, 17)) %>%
                 pull(CVE_ZM)

# Se elimina la variable CVE_ZM
Migrantes <- Migrantes %>%
              select(-CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Metropolitano")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_ZM"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil hace 5 años a nivel municipal, 2015 - 2020

Matriz de movilidad estudiantil por zonas metropolitanas
Nivel municipal
CVE_ZM 01.01 02.01 02.02 02.03 03.01 03.02 04.01 05.01 05.02 05.03 05.04 05.05 06.01 06.02 07.01 07.02 08.01 08.02 08.03 08.04 09.01 10.01 11.01 11.02 11.03 11.04 11.06 11.07 12.01
01.01 330807 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79 0 0 79 132 0 0 0 59
02.01 0 112987 148 342 0 0 0 0 0 0 0 0 0 0 0 0 0 27 0 0 0 0 0 0 0 0 0 0 0
02.02 0 16 266099 42 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
02.03 0 331 106 489724 0 0 0 0 0 0 0 0 0 0 0 0 79 0 0 0 0 0 0 0 0 0 79 0 0
03.01 0 40 0 0 75849 146 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 21 0 0 0 0 0 0 0
03.02 0 0 0 55 284 92491 0 0 0 0 0 0 0 0 0 0 0 0 0 0 48 0 0 0 0 0 0 0 0
04.01 0 0 0 0 0 0 79728 0 0 0 0 0 0 0 0 0 0 0 0 0 25 0 0 0 0 0 0 0 0
05.01 21 0 0 0 0 0 0 348180 22 0 78 0 0 0 0 0 0 0 0 0 0 381 0 0 67 0 0 0 0
05.02 0 0 0 0 0 0 0 33 95197 8 157 0 0 0 0 0 0 0 0 0 0 12 0 12 0 0 0 0 0
05.03 0 0 0 0 0 0 0 0 3 48571 34 6 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0
05.04 0 0 0 0 0 0 0 112 0 0 272903 0 0 0 0 0 0 0 0 0 5 0 0 16 0 0 0 0 0
05.05 0 0 0 0 0 0 0 0 23 50 49 24555 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
06.01 0 0 0 24 0 0 0 0 0 0 0 0 87818 190 0 0 0 0 0 0 100 0 0 24 0 0 0 0 0
06.02 0 0 0 0 0 0 0 0 0 0 0 0 715 34841 0 0 0 0 0 0 12 0 0 0 0 0 0 0 0
07.01 16 0 0 0 0 0 0 0 0 0 2 0 0 0 102068 170 0 0 0 0 0 0 0 0 0 0 0 0 0
07.02 0 0 0 0 0 0 0 0 0 0 0 0 0 0 65 226417 0 0 0 0 144 0 0 0 0 0 0 0 9
08.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 282455 0 0 138 0 0 0 0 0 0 0 0 0
08.02 0 0 0 0 0 0 0 18 0 0 0 0 0 0 0 0 1144 53425 11 0 0 0 0 0 0 0 0 0 0
08.03 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 18 32027 0 0 0 0 0 0 0 0 0 0
08.04 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 399731 0 0 0 0 0 0 0 0 0
09.01 7 0 26 4 44 0 0 0 0 0 0 0 0 0 0 4 37 0 0 69 5164297 29 0 33 28 0 0 0 66
10.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 204068 0 42 0 0 0 0 0
11.01 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 28 174058 317 119 0 147 0 0
11.02 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 52061 675 0 293 210 0
11.03 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0 10 665 497020 0 300 1463 0
11.04 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79 79 87 29005 23 0 0
11.06 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 56 473 484 0 149649 80 0
11.07 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 34 0 21 835 2001 0 310 69321 0
12.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 66 0 0 0 48 0 0 0 204590
12.02 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 295 0 0 0 0 0 0 0 332
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

################################################################################
tabla1 <- lapply(1, function(x){
                         Migrantes %>%
                          as.data.frame() %>%
                           tibble::rownames_to_column(var = "rn") %>% 
                            melt(., id.vars = "rn", variable.name = "cn") %>%
                             mutate_if(is.factor, as.character) %>%
                              mutate(value = ifelse((.$rn != .$cn), value, 0)) %>% 
                               filter(value > 0) %>%
                                dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                 column_to_rownames(., var = "rn") 
}
)
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (metropolitano).pdf"
 
## Gráficos a nivel metropolitano
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))
Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2020.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2020 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
ZM <- ZM_2020 %>% 
       select(CVE_ZM, NOM_ZM) %>% 
        distinct(CVE_ZM, NOM_ZM) %>%
         mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
          pull(CVE_ZM) %>%
           as.list()

NOM_ZM_CF <- ZM_2020 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)
################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
#p <- data.frame(ZM = ZM,
 #               filtro_zm = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel metropolitano.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Filtro a nivel metropolitano.xlsx"), colNames = TRUE) %>%
               pull(filtro_zm)

################################################################################

tabla1 <- metropolitan_flows(tabla = Migrantes, 
                             filtro_zm = ZM, 
                             filtro_mig = filtro_mig, 
                             Emigrantes = Emigrantes, 
                             Inmigrantes = Inmigrantes, 
                             group = "Otras zonas metropolitanas")

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, zm[i])
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))

total_tablas <- totales(tabla1, ZM)
porcentajes_tablas <- porcentajes(tabla1, ZM)

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))

#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (metropolitano)_individual.pdf"
 
## Gráficos a nivel metropolitano
chord_diagram_graph(file = file, 
                    width = 8, 
                    height = 8, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.15, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE, 
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Etiquetas ZM a nivel metropolitano.pdf"

## Etiquetas a nivel zona metropolitana
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1,
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2020.RData"))

ZM <- lapply(1:length(zm), function(x){
                 ZM_2020 %>% 
                  select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                   filter(CVE_ZM %in% zm[x])  %>% 
                    pull(CVE_MUN)
})


Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
}
)

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################

# Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudio
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)


tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Metropolitano) 2020.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Metropolitano) 2020.RData"))
Indicadores de movilidad estudiantil
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 1 137 351 1 081 805 318 855 14 044 19 109 −5 065 33 153 2.531 3.444 −0.9 −38 218
02.01 440 624 422 238 112 987 638 857 −219 1 495 0.296 0.397 −0.1 −1 714
02.02 1 042 395 1 004 592 266 099 596 870 −274 1 466 0.116 0.170 −0.1 −1 740
02.03 2 036 832 1 951 173 486 494 6 130 4 869 1 261 10 999 0.615 0.488 0.1 −9 738
03.01 290 063 279 213 75 849 462 495 −33 957 0.325 0.348 0.0 −990
03.02 350 193 331 218 92 491 577 251 326 828 0.339 0.147 0.2 −502
04.01 293 199 280 245 79 728 576 2 402 −1 826 2 978 0.402 1.675 −1.3 −4 804
05.01 1 369 966 1 299 574 328 766 20 955 24 007 −3 052 44 962 3.140 3.597 −0.5 −48 014
05.02 374 001 354 352 91 912 3 927 4 053 −126 7 980 2.157 2.226 −0.1 −8 106
05.03 207 994 197 078 48 070 743 1 381 −638 2 124 0.734 1.364 −0.6 −2 762
05.04 1 028 156 975 410 263 661 10 636 11 307 −671 21 943 2.123 2.257 −0.1 −22 614
05.05 106 988 101 421 23 710 1 000 1 899 −899 2 899 1.919 3.645 −1.7 −3 798
06.01 326 478 314 261 74 868 15 899 17 782 −1 883 33 681 9.925 11.101 −1.2 −35 564
06.02 143 572 136 775 34 451 1 510 790 720 2 300 2.154 1.127 1.0 −1 580
07.01 397 226 374 566 100 794 2 204 7 470 −5 266 9 674 1.142 3.872 −2.7 −14 940
07.02 846 364 805 290 216 441 11 606 21 531 −9 925 33 137 2.811 5.214 −2.4 −43 062
08.01 982 589 943 151 281 381 1 677 4 275 −2 598 5 952 0.348 0.888 −0.5 −8 550
08.02 211 810 201 317 51 274 3 464 2 820 644 6 284 3.354 2.730 0.6 −5 640
08.03 121 201 115 066 31 832 443 1 634 −1 191 2 077 0.750 2.766 −2.0 −3 268
08.04 1 505 714 1 441 982 399 731 238 507 −269 745 0.032 0.069 0.0 −1 014
Fuente: Estimaciones del CONAPO.

Migración intrametropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a estudiar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intrametropolitana.RDS"))

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
MR <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2020.RDS"))

Residentes <- lapply(1:length(zm), function(x){
                                     MR[[x]] %>% 
                                      as.data.frame() %>%
                                       melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                        mutate_at(vars(3), as.numeric) %>%
                                         filter(CVE_MUN == CVE_MUN_ASI)  %>%
                                          summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                           mutate(CVE_ZM = !!paste0(zm[x])) 
}
)

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- lapply(1:length(zm), function(x){
                                      MR[[x]] %>% 
                                       as.data.frame() %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                            mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################

# Población que entra a la entidad para estudiar
Emigrantes <- lapply(1:length(zm), function(x){
                                    MR[[x]] %>% 
                                     tibble::column_to_rownames(var = "CVE_MUN") %>%
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                            summarize(Emigrantes=  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)


tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intrametropolitano) 2020.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intrametropolitano) 2020.RData"))
Indicadores de movilidad estudiantil
Zonas Intrametropolitano
CVE_ZM Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 1 137 351 1 081 805 318 855 11 952 11 952 0 23 904 2.15 2.15 0.0 −23 904
02.01 440 624 422 238 112 987 0 0 0 0 0.00 0.00 0.0 0
02.02 1 042 395 1 004 592 266 099 0 0 0 0 0.00 0.00 0.0 0
02.03 2 036 832 1 951 173 486 494 3 230 3 230 0 6 460 0.32 0.32 0.0 −6 460
03.01 290 063 279 213 75 849 0 0 0 0 0.00 0.00 0.0 0
03.02 350 193 331 218 92 491 0 0 0 0 0.00 0.00 0.0 0
04.01 293 199 280 245 79 728 0 0 0 0 0.00 0.00 0.0 0
05.01 1 369 966 1 299 574 328 766 19 414 19 414 0 38 828 2.91 2.91 0.0 −38 828
05.02 374 001 354 352 91 912 3 285 3 285 0 6 570 1.80 1.80 0.0 −6 570
05.03 207 994 197 078 48 070 501 501 0 1 002 0.49 0.49 0.0 −1 002
05.04 1 028 156 975 410 263 661 9 242 9 242 0 18 484 1.85 1.85 0.0 −18 484
05.05 106 988 101 421 23 710 845 845 0 1 690 1.62 1.62 0.0 −1 690
06.01 326 478 314 261 74 868 12 950 12 950 0 25 900 8.08 8.08 0.0 −25 900
06.02 143 572 136 775 34 451 390 390 0 780 0.56 0.56 0.0 −780
07.01 397 226 374 566 100 794 1 274 1 274 0 2 548 0.66 0.66 0.0 −2 548
07.02 846 364 805 290 216 441 9 976 9 976 0 19 952 2.42 2.42 0.0 −19 952
08.01 982 589 943 151 281 381 1 074 1 074 0 2 148 0.22 0.22 0.0 −2 148
08.02 211 810 201 317 51 274 2 151 2 151 0 4 302 2.08 2.08 0.0 −4 302
08.03 121 201 115 066 31 832 195 195 0 390 0.33 0.33 0.0 −390
08.04 1 505 714 1 441 982 399 731 0 0 0 0 0.00 0.00 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermetropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2020 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2020 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '1' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2020 %in% '0' & .$I_ASI_ZM_2020 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/MC_intermetropolitana.RDS"))

Indicadores

Se realizan cálculos generales de migración
- Residentes
- Inmigrantes
- Emigrantes
- % Inmigrantes
- % Emigrante
- Migración bruta
- Migración Neta
- % Tasa de migración bruta
- % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Matriz de movilidad estudiantil a nivel intermunicipal 2020.RData"))

ZM <- lapply(1:length(zm), function(x){
                    ZM_2020 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% zm[x])  %>% 
                       pull(CVE_MUN)
})


Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
}
)

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################

# Población que entra a la entidad para estudiar
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)


tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intermetropolitano) 2020.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2020/04_Movilidad estudiantil/Indicadores de MEst por ZM 2020 (Intermetropolitano) 2020.RData"))
Indicadores de movilidad estudiantil
Zonas Intermetropolitano
CVE_ZM Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 1 137 351 1 081 805 0 2 092 7 157 −5 065 9 249 0.377 1.290 −0.9 −14 314
02.01 440 624 422 238 0 638 857 −219 1 495 0.296 0.397 −0.1 −1 714
02.02 1 042 395 1 004 592 0 596 870 −274 1 466 0.116 0.170 −0.1 −1 740
02.03 2 036 832 1 951 173 0 2 900 1 639 1 261 4 539 0.291 0.164 0.1 −3 278
03.01 290 063 279 213 0 462 495 −33 957 0.325 0.348 0.0 −990
03.02 350 193 331 218 0 577 251 326 828 0.339 0.147 0.2 −502
04.01 293 199 280 245 0 576 2 402 −1 826 2 978 0.402 1.675 −1.3 −4 804
05.01 1 369 966 1 299 574 0 1 541 4 593 −3 052 6 134 0.231 0.688 −0.5 −9 186
05.02 374 001 354 352 0 642 768 −126 1 410 0.353 0.422 −0.1 −1 536
05.03 207 994 197 078 0 242 880 −638 1 122 0.239 0.869 −0.6 −1 760
05.04 1 028 156 975 410 0 1 394 2 065 −671 3 459 0.278 0.412 −0.1 −4 130
05.05 106 988 101 421 0 155 1 054 −899 1 209 0.297 2.023 −1.7 −2 108
06.01 326 478 314 261 0 2 949 4 832 −1 883 7 781 1.841 3.017 −1.2 −9 664
06.02 143 572 136 775 0 1 120 400 720 1 520 1.598 0.571 1.0 −800
07.01 397 226 374 566 0 930 6 196 −5 266 7 126 0.482 3.211 −2.7 −12 392
07.02 846 364 805 290 0 1 630 11 555 −9 925 13 185 0.395 2.798 −2.4 −23 110
08.01 982 589 943 151 0 603 3 201 −2 598 3 804 0.125 0.665 −0.5 −6 402
08.02 211 810 201 317 0 1 313 669 644 1 982 1.271 0.648 0.6 −1 338
08.03 121 201 115 066 0 248 1 439 −1 191 1 687 0.420 2.436 −2.0 −2 878
08.04 1 505 714 1 441 982 0 238 507 −269 745 0.032 0.069 0.0 −1 014
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
extrafont 0.19 CRAN (R 4.3.0)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
showtext 0.9-6 CRAN (R 4.3.1)
showtextdb 3.0 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
sysfonts 0.8.8 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.0 CRAN (R 4.3.1)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.